/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/render', 'N/file', 'N/search'], function (record, render, file, search) {
    function beforeLoad(context) {
        if (context.type === 'view') {
            try {
                var rec = record.load({
                    type: record.Type.PURCHASE_ORDER,
                    id: context.newRecord.id,
                    isDynamic: true
                });
                var po = {};
                po.printTimes = rec.getValue('custbody_print_times');
                po.memo = rec.getText('memo');
                var vendorRec = record.load({
                    type: 'vendor',
                    id: rec.getValue('entity'),
                    isDynamic: true
                });
                po.vendor = vendorRec.getText('companyname');
                po.subsidiary = rec.getText('subsidiary');

                var subsidiaryRec = record.load({
                    type: 'subsidiary',
                    id: rec.getValue('subsidiary'),
                    isDynamic: true
                });
                var baseCurrency = subsidiaryRec.getText('currency');
                po.baseCurrency = baseCurrency;

                po.contractno = rec.getText('custbody_contractno');
                po.date = rec.getText('trandate');
                po.tranid = rec.getValue('tranid');
                po.currency = rec.getText('currency');
                po.exchangerate = rec.getText('exchangerate');
                po.purchaseCountry = rec.getText('custbody_purchasecountry');
                po.shipmethod = rec.getText('shipmethod');
                po.address = subsidiaryRec.getText('shippingaddress_text');

                var items = [];
                var lineCount = rec.getLineCount('item');
                var totalQuantity = 0;
                var totalAmount = 0;
                var totalGrossAmount = 0;
                //log.debug('1',JSON.stringify(rec.getSublistFields('item')));
                for (var i = 0; i < lineCount; i++) {
                    var item = {};
                    rec.selectLine('item', i);
                    item.lineNumber = i + 1;

                    item.itemsubtype = rec.getCurrentSublistText('item', 'itemsubtype');
                    item.itemtype = rec.getCurrentSublistText('item', 'itemtype');
                    //log.debug(item.itemtype, item.itemsubtype);
                    var itemId = rec.getCurrentSublistValue('item', 'item');

                    var results = search.create({
                        type: 'item',
                        columns: ['type'],
                        filters: [['internalid', 'is', itemId]]
                    }).run().getRange(0, 1);
                    var itemRec = record.load({
                        type: results[0].recordType,
                        id: itemId
                    });
                    if (results[0].recordType === 'inventoryitem') {
                        item.size = itemRec.getText('custitem_door_width');
                    } else {
                        item.size = itemRec.getText('custitem_size');
                    }
                    item.sku = itemRec.getText('custitem_child_sku');
                    item.name = itemRec.getText('displayname');
                    item.code = rec.getCurrentSublistText('item', 'item');
                    item.color = itemRec.getText('custitem_color');
                    item.colorNumber = itemRec.getText('custitem_color_number');
                    item.flowerType = itemRec.getText('custitem_flower_type');
                    item.flowerTypeColor = itemRec.getText('custitem_flower_type_color');

                    item.quantity = Number(rec.getCurrentSublistText('item', 'quantity').replace(/,/g, ""));
                    totalQuantity += item.quantity;
                    item.unit = rec.getCurrentSublistText('item', 'units');
                    item.rate = rec.getCurrentSublistText('item', 'rate');

                    item.amount = Number(rec.getCurrentSublistText('item', 'amount').replace(/,/g, ""));
                    item.grossAmount = Number(rec.getCurrentSublistText('item', 'grossamt').replace(/,/g, ""));
                    totalAmount += item.amount;
                    totalGrossAmount += item.grossAmount;
                    item.deliveryDate = rec.getCurrentSublistText('item', 'custcol_delivery_date');
                    item.remarks = rec.getCurrentSublistText('item', 'custcol_remarks');

                    items.push(item);
                }
                po.items = items;
                po.totalAmount = totalAmount.toFixed(2);
                po.totalGrossAmount = totalGrossAmount.toFixed(2);
                po.totalTaxAmount = (po.totalGrossAmount - po.totalAmount).toFixed(2);

                po.baseCurrencyTotalAmount = (po.totalAmount * Number(po.exchangerate)).toFixed(2);
                po.baseCurrencyTotalGrossAmount = (po.totalGrossAmount * Number(po.exchangerate)).toFixed(2);
                po.baseCurrencytotalTaxAmount = (po.totalTaxAmount * Number(po.exchangerate)).toFixed(2);

                po.totalQuantity = totalQuantity;
                log.debug('po', po);

                //调用模板文件
                var renderer = render.create();
                renderer.templateContent = file.load(1298).getContents();
                renderer.addCustomDataSource({
                    format: render.DataSource.JSON,
                    alias: 'po',
                    data: JSON.stringify(po)
                });
                var pdfFile = renderer.renderAsPdf();
                //PDF文件存放文件夹ID
                pdfFile.folder = 185;
                pdfFile.name = context.newRecord.id + new Date().getTime() + '.pdf';
                var fileId = pdfFile.save();
                var invalidFile = record.create({type: 'customrecord_invalid_file_id'});
                invalidFile.setValue('custrecord_invalid_file_id', fileId);
                invalidFile.save();
                var File = file.load(fileId);
                var pdfurl = File.url;
                var form = context.form;
                form.addButton({
                    id: 'custpage_button',
                    label: '打印采购单',
                    functionName: "window.open('" + pdfurl + "');"
                });
            } catch (e) {
                log.error(e.name, e.message);
            }

        }
    }


    return {
        beforeLoad: beforeLoad
    };
});
